package com.gql.optional;

import com.gql.optional.bean.Boy;
import com.gql.optional.bean.Girl;
import jdk.nashorn.internal.runtime.regexp.joni.constants.OPCode;
import org.junit.jupiter.api.Test;

import java.util.Optional;

/**
 * description: 测试Optional类
 *      为了避免在程序中出现空指针异常而出现的
 *      ofNull(T t)
 *      orElse(T t)
 * @author: gql
 * @date: 2022/04
 */
public class OptionalTest {

    /**
     * 1. Optional.of(T t) 创建一个Optional实例, t不允许为null
     */
    @Test
    public void ofTest() {
        Girl girl = new Girl();
        girl = null;
        Optional<Girl> optionalGirl = Optional.of(girl);
        System.out.println("optionalGirl = " + optionalGirl);
    }

    /**
     * 2. Optional.ofNullable(T t)  t可以为null
     */
    @Test
    public void ofNullableTest() {
        Girl girl = new Girl();
        girl = null;
        Optional<Girl> optionalGirl = Optional.ofNullable(girl);
        System.out.println("optionalGirl = " + optionalGirl);
    }

    /**
     * 3. Optional.empty( ) 创建一个Optional实例
     */
    @Test
    public void emptyTest() {

    }

    /**
     * 使用场景
     */
    @Test
    public void OptionalTest() {
        Boy boy = new Boy();
        boy = null;
        String girlName = getGirlName3(boy);
        System.out.println("girlName = " + girlName);
    }

    /**
     * 原始版
     * @param boy
     * @return
     */
    private String getGirlName1(Boy boy) {
        return boy.getGirl().getName();
    }

    /**
     * 之前写法
     * @param boy
     * @return
     */
    private String getGirlName2(Boy boy) {
        if (null != boy) {
            Girl girl = boy.getGirl();
            if (null != girl) {
                return girl.getName();
            }
        }
        return null;
    }

    /**
     * 使用Optional
     * @param boy
     * @return
     */
    private String getGirlName3(Boy boy) {
        Optional<Boy> boyOptional = Optional.ofNullable(boy);
        // boy为null,就手动补充
        Boy tempBoy = boyOptional.orElse(new Boy(new Girl("迪丽热巴")));

        Optional<Girl> girlOptional = Optional.ofNullable(tempBoy.getGirl());
        // girl为null,就手动补充
        Girl tempgirl = girlOptional.orElse(new Girl("赵丽颖"));

        return tempgirl.getName();
    }
}

